
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;



/**
 * @author User
 * @version 1.0
 * @created 10-sep-2012 11:23:27 a.m.
 */
public class SensorCH4 extends Thread {

	private Mina mina;
	private JavaCPN Server1;
	private boolean finalizar=false;
        private double nivel_max;
        //----------------------------
        //------Parte Implementada por el negro
        public static boolean stop;
        private int port;
	private String host;
        ByteArrayInputStream fromCPN;
        String recibirDeCPN;
        //se implementaron los metodos conectarse, recibir, y enviar.
        //------2 variabales agregadas-------------------------------
        //-----------------------------
	public SensorCH4(){
        this.Server1 = new JavaCPN();
	}

	public void finalize() throws Throwable {
		super.finalize();
	}
	/**
	 * 
	 * @param Mina
	 */
	public void SensorCH4(Mina mina){
            this.mina= mina;
            this.Server1 = new JavaCPN();
        }

	

        	
        
	private boolean Conectar(){
		  try {
              Server1.connect("localhost",9001);
           //Server.connect(host, port);
            System.out.println("Server Conectado");
            stop=true;
                        } catch (IOException ex) {
            System.err.println("no se encontro el host " + host);
            stop=false;
                                   }

		return stop;//stop puede ser true or false si se conecto o no
	}

	private void Enviar(String nivel){
            fromCPN=EncodeDecode.encode(nivel);
              try {
              Server1.send(fromCPN);
            // TODO Auto-generated catch block}
                  } catch (SocketException ex) {
            Logger.getLogger(SensorH2O.class.getName()).log(Level.SEVERE, null, ex);
                  }
	}

	private String Medir(){
            String nivel;
            if(mina.getCH4()>nivel_max){//si el nivel es demasiado alto
               nivel="alto" ;
            }
            else{nivel="bajo";}
        return nivel;
	}

	private void RecibirSenal(){
                 try {
                 recibirDeCPN = EncodeDecode.decodeString(Server1.receive());
                 System.out.println(recibirDeCPN);
                } catch (SocketException ex)
                {
                Logger.getLogger(SensorH2O.class.getName()).log(Level.SEVERE, null, ex);
                }

	}

	public void run(){
          while (this.Conectar()==false){
            this.Conectar();}
            while (finalizar==false){
            RecibirSenal();
            Enviar("bajo");
            }


	}
}//end SensorCH4